import * as mysql from 'mysql2/promise';  
import { databaseConfig } from './config/databaseConfig';  
  
// 自定义错误类  
class DatabaseError extends Error {  
  constructor(message: string) {  
    super(message);  
    Object.setPrototypeOf(this, DatabaseError.prototype);  
  }  
}  
  
export class DatabaseService {  
  private connection: mysql.Connection | null = null;  
  
  constructor() {  
    this.initConnection();  
  }  
  
  private async initConnection(): Promise<void> {  
    try {  
      this.connection = await mysql.createConnection(databaseConfig);  
    } catch (error) {  
      // 使用类型断言或自定义错误类  
      throw new DatabaseError('Error creating database connection: ' + (error as Error).message);  
    }  
  }  
  
  private async ensureConnection(): Promise<void> {  
    if (!this.connection) {  
      await this.initConnection();  
    }  
  }  
  
  public async insertData(tableName: string, data: Map<string, any>): Promise<any> {  
    try {  
      await this.ensureConnection();  
      // 获取Map对象的键和值  
      const columns = Array.from(data.keys()).join(',');  
      const placeholders = Array.from(data.keys()).map(() => '?').join(', ');  
      const values = Array.from(data.values());  
      const cleanedValues = values.map(value => {  
        return value === undefined ? null : value;  
      });  
      // 构建SQL语句  
      const sql = `INSERT INTO ${tableName} (${columns}) VALUES (${placeholders})`;  
    
      try {  
        // 执行SQL语句  
        const result = await this.connection!.execute(sql, cleanedValues);  
        return result;  
      } catch (error) {  
        // 处理执行SQL时的错误  
        throw new DatabaseError('Error inserting data into database: ' + (error as Error).message);  
      }  
    } catch (error) {  
      // 处理在ensureConnection或其他地方可能发生的错误  
      throw new DatabaseError('Error ensuring database connection or inserting data: ' + (error as Error).message);  
    }  
  }

  public async closeConnection(): Promise<void> {  
    try {  
      if (this.connection) {  
        await this.connection.end();  
        this.connection = null;  
      }  
    } catch (error) {  
      console.error('Error closing database connection:', error);  
    }  
  }  
}